package com.month.ai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.month.ai.entity.AiInteractionLog;
import com.month.ai.mapper.AiInteractionLogMapper;
import com.month.ai.service.AiInteractionLogService;
import com.month.ai.vo.SimpleMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class AiInteractionLogServiceImpl extends ServiceImpl<AiInteractionLogMapper, AiInteractionLog> implements AiInteractionLogService {





    @Override
    @Transactional
    public void SaveMessages(String conversationId, List<Message> messages) {
        for (Message message : messages) {
            AiInteractionLog aiInteractionLog = new AiInteractionLog();
            aiInteractionLog.setContent(message.getText());
            aiInteractionLog.setSessionId(conversationId); //会话id
            aiInteractionLog.setMessageType(message.getMessageType().name());
            aiInteractionLog.setStatus(0);//执行状态
            this.save(aiInteractionLog);
        }
    }

    @Override
    public List<Message> getMessages(String sessionId, int lastN) {
        // 查询数据库获取指定会话ID的最后lastN条日志
        LambdaQueryWrapper<AiInteractionLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AiInteractionLog::getSessionId, sessionId);
        queryWrapper.orderByAsc(AiInteractionLog::getCreatedAt);
        List<AiInteractionLog> logs = this.list(queryWrapper);
        // 将日志列表转换为消息列表
        return logs.stream().map(log -> SimpleMessage.createMessage(log.getMessageType(), log.getContent())) // 假设请求文本为消息内容
                .collect(Collectors.toList());
    }
}
